namespace AtomicCms.Web.Areas.Admin.Controllers
{
    using System.Collections.Generic;
    using System.Security.Principal;
    using System.Web.Mvc;
    using Common.Entities;
    using Core.Extensions;
    using Core.Filters;
    using Services;
    using Web.Controllers;

    [Authorize]
    public class CmsPageController : AtomicCmsController
    {
        private readonly PageService pageService;
        public CmsPageController(PageService pageService)
        {
            this.pageService = pageService;
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ViewResult Edit(int? id)
        {
            if (null != id)
            {
                CmsPage entry = this.pageService.Load(id.Value);
                return this.View(entry);
            }

            return View(new CmsPage());
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        [CurrentUserFilter]
        public ActionResult Edit(int id, FormCollection forms, string userName)
        {
            CmsPage pageFromDb = this.pageService.Load(id);
            UpdateModel(pageFromDb, forms.ToValueProvider());
            pageFromDb.TagString = forms.GetValue("Tags");
            if (pageFromDb.IsValid)
            {
                this.pageService.Save(pageFromDb, userName);
                TempData["SuccessResult"] = "Items was successfully saved";
                return RedirectToAction("Edit", new {id = pageFromDb.Id});
            }

            ModelState.AddModelErrors(pageFromDb.GetRuleViolations());
            return View(pageFromDb);
        }

        public ViewResult List()
        {
            IEnumerable<CmsPage> allPages = this.pageService.LoadAll();
            return View(allPages);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(int id)
        {
            this.pageService.Delete(id);
            return new EmptyResult();
        }
    }
}